package {
	import com.moorwind.chartservice.data.ChartVO;
	import com.moorwind.chartservice.events.TokenEvent;
	import com.moorwind.chartservice.utils.ChartConfig;
	import com.moorwind.chartservice.utils.ChartParser;
	import com.moorwind.chartservice.utils.CustomChartConfig;
	import com.moorwind.chartservice.utils.NetUtil;
	import com.moorwind.chartservice.utils.TokenUtil;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextField;

	public class ChartTest extends Sprite
	{
		private var textField:TextField;
		
		public function ChartTest()
		{
			textField = new TextField();
			textField.width = 640;
			textField.height = 480;
			textField.wordWrap = true;
			textField.multiline = true;
			textField.selectable = true;
			textField.y = 30;
			
			addChild(textField);
			
			createButton();
			CustomChartConfig.updateConfig();
		}
		
		private function createButton():void
		{
			var postBtn:Sprite = drawButton();
			addChild(postBtn);
			postBtn.addEventListener(MouseEvent.CLICK, testPost);
			
			var getBtn:Sprite = drawButton();
			getBtn.x = 150
			addChild(getBtn);
			getBtn.addEventListener(MouseEvent.CLICK, testGet);
		}
		
		private function drawButton():Sprite
		{
			var sp:Sprite = new Sprite();
			sp.graphics.beginFill(0);
			sp.graphics.drawRect(0,0,100,20);
			sp.graphics.endFill();
			sp.buttonMode = true;
			return sp;
		}
		
		
		
		public function testPost(e:Event = null):void
		{
			var tokenUtil:TokenUtil = new TokenUtil();
			tokenUtil.addEventListener(TokenEvent.TOKEN_KEY, onGetToken_handler);
			tokenUtil.getToken(ChartConfig.instance.CHART_TOKEN);
		}
		
		public function onGetToken_handler(e:TokenEvent):void
		{			
			var chart:ChartVO = new ChartVO();
			chart.userName = "GameChart";
			chart.userId = "1303969295";
			chart.userLink = "http://www.google.com/reader/view/#overview-page";
			chart.userImage = "http://b4.ac-images.cdnmyspace.cn/cnimages01/1/s_8ea4e4abd024297127ae2afaeab183fb.jpg";
			chart.userLargeImage = "http://b4.ac-images.cdnmyspace.cn/cnimages01/1/s_8ea4e4abd024297127ae2afaeab183fb.jpg";
			chart.platform = "myspace.cn";
			chart.score = 100;
			chart.chartId = 1;
			chart.chartName = "TestChart";
			
			NetUtil.postChartData(chart, e.token, onData_handler, onError_handler);
		}
		
		public function testGet(e:Event = null):void
		{
			NetUtil.getChartData(1, onData_handler, onError_handler);
		}
		
		private function onData_handler(e:Event):void
		{			
			textField.appendText( ChartParser.parserChart(e.target.data) + "\n");
		}
		
		private function onError_handler(e:Event):void
		{
			textField.appendText(e + "\n");
		}
	}
}
